import {
	decodeElement
} from '../.././utils/decode-element.js'
import $moment from '../.././utils/moment.js'
import TIM from '../.././utils/tim-wx.js'

const state = {
	isSdkReady: false,
	isCalling: false,
	systemInfo: null,
	groupList: [],
	currentGroupMemberList: [],
	count: 15,
	isLoading: false,
	myTimInfo: {},
	userTimProfile: {},
	blacklist: [],
	allConversation: [], // 所有的conversation
	currentConversationID: '', // 当前聊天对话ID
	currentConversation: {}, // 当前聊天对话信息
	currentMessageList: [], // 当前聊天消息列表
	nextReqMessageID: '', // 下一条消息标志
	isCompleted: false, // 当前会话消息是否已经请求完毕
	isLoading: false // 是否正在请求
}

const formatTime = date => {
	if ($moment(date).isToday()) {
		let prefix = $moment(date).getTimePeriodPrefix(),
			result = $moment(date).format('HH:mm');
		prefix && (result = `${prefix} ${result}`)
		return result
	}
	return $moment(date).format('YYYY-MM-DD')
}

const mutations = {
	// 重置用户
	RESET_USER: (state) => {
		state.blacklist = []
		state.userTimProfile = {}
		state.myTimInfo = {}
	},
	// 重置群
	RESET_GROUP: (state) => {
		state.groupList = []
		state.currentGroupProfile = {}
		state.currentGroupMemberList = []
	},
	RESET_ALL_CONVERSATION: (state) => {
		state.allConversation = []
		uni.setStorageSync('allConversation', [])
	},
	RESET_CURRENT_MEMBER_LIST: () => {
		state.currentGroupMemberList = []
	},
	RESET_CURRENT_CONVERSATION: (state) => {
		state.currentConversationID = '' // 当前聊天对话ID
		state.currentConversation = {} // 当前聊天对话信息
		state.currentMessageList = [] // 当前聊天消息列表
		state.nextReqMessageID = '' // 下一条消息标志
		state.isCompleted = false // 当前会话消息是否已经请求完毕
		state.isLoading = false // 是否正在请求
	},
	// 更新用户
	UPDATE_MY_INFO: (state, myTimInfo) => {
		state.myTimInfo = myTimInfo
	},
	CONVERSATION_SEARCH: (state, search) => {
		const allConversation = uni.getStorageSync('allConversation')
		state.allConversation = allConversation.filter(item => {
			const {
				type,
				userProfile,
				groupProfile
			} = item;
			return type !== '@TIM#SYSTEM' && (userProfile ? userProfile
				.nick.includes(
					search) : groupProfile.name.includes(
					search))
		})
	},
	UPDATE_ALL_CONVERSATION: (state, list) => {
		for (let i = 0; i < list.length; i++) {
			if (list[i].lastMessage && (typeof list[i].lastMessage.lastTime === 'number')) {
				let date = new Date(list[i].lastMessage.lastTime * 1000)

				list[i].lastMessage._lastTime = formatTime(date)
			}
		}
		state.allConversation = list
		uni.setStorageSync('allConversation', list)
	},
	UPDATE_GROUP_LIST: (state, groupList) => {
		state.groupList = groupList
		// console.log('state.groupList',state.groupList)
	},
	CANCEL_GROUP: (state, groupID) => {
		state.groupList = state.groupList.filter(item => item.groupID !== groupID)
	},
	ADD_GROUP: (state, groupItem) => {
		state.groupList = state.groupList.concat(groupItem)
	},
	UPDATE_BLACK_LIST: (state, blacklist) => {
		state.blacklist.push(blacklist)
	},
	RECEIVE_MESSAGE: (state, messageList) => {
		let list = [...messageList]
		for (let i = 0; i < list.length; i++) {
			let message = list[i]
			list[i].virtualDom = decodeElement(message)
			let date = new Date(message.time * 1000)
			list[i].newtime = formatTime(date)
		}
		state.currentMessageList = [...state.currentMessageList, ...list]
	},
	UPDATE_CURRENT_CONVERSATION: (state, conversation) => {
		state.currentConversation = conversation
		state.currentConversationID = conversation.conversationID
	},
	UPDATE_CURRENT_GROUPME_MBERLIST: (state, groupMemberList) => {
		state.currentGroupMemberList = [...state.currentGroupMemberList, ...groupMemberList]
	},
	SET_BLACK_LIST: (state, blacklist) => {
		state.blacklist = blacklist
	},
	SET_SDK_READY: (state, payload) => {
		state.isSdkReady = payload
	},
	SET_SYSTEM__INFO: (state, payload) => {
		state.systemInfo = payload
	},
	SHOW_TOAST: (state, payload) => {
		uni.showToast({
			title: payload.title,
			icon: payload.icon || 'none',
			duration: payload.duration || 800
		})
	},
	SEND_MESSAGE: (state, message) => {
		message.virtualDom = decodeElement(message)
		let date = new Date(message.time * 1000)
		message.newtime = formatTime(date)
		state.currentMessageList.push(message)
		setTimeout(() => {
			uni.pageScrollTo({
				scrollTop: 99999
			})
		}, 800)
	},
	// 历史头插消息列表
	// 小程序问题，在渲染的时候模板引擎不能处理函数，所以只能在渲染前处理好message的展示问题
	UNSHIFTMESSAGELIST: (state, messageList) => {
		let list = [...messageList]
		for (let i = 0; i < list.length; i++) {
			let message = list[i]
			list[i].virtualDom = decodeElement(message)
			let date = new Date(message.time * 1000)
			list[i].newtime = formatTime(date)
		}
		state.currentMessageList = [...list, ...state.currentMessageList]
	},
}

const actions = {
	resetStore({
		commit
	}) {
		commit('RESET_GROUP')
		commit('RESET_USER')
		commit('RESET_CURRENT_CONVERSATION')
		commit('RESET_ALL_CONVERSATION')
	},
	// 获取消息列表
	getMessageList({
		commit,
		state
	}) {
		const {
			currentConversationID,
			nextReqMessageID
		} = state
		// 判断是否拉完了，isCompleted 的话要报一下没有更多了
		if (!state.isCompleted) {
			// 如果请求还没回来，又拉，此时做一下防御
			if (!state.isLoading) {
				state.isLoading = true
				uni.$Tim.getMessageList({
					conversationID: currentConversationID,
					nextReqMessageID: nextReqMessageID,
					count: 15
				}).then(res => {
					state.nextReqMessageID = res.data.nextReqMessageID
					commit('UNSHIFTMESSAGELIST', res.data.messageList)
					if (res.data.isCompleted) {
						state.isCompleted = true
					}
					state.isLoading = false
				}).catch(err => {
					console.log(err)
				})
			} else {
				uni.showToast({
					title: '你拉的太快了',
					icon: 'none',
					duration: 500
				})
			}
		} else {
			uni.showToast({
				title: '没有更多啦',
				icon: 'none',
				duration: 1500
			})
		}
	},
	checkoutConversation({
		commit,
		dispatch
	}, {
		url,
		conversationID,
		oid
	}) {
		commit('RESET_CURRENT_CONVERSATION')
		uni.$Tim.setMessageRead({
			conversationID
		})
		return uni.$Tim.getConversationProfile(conversationID)
			.then(({
				data: {
					conversation
				}
			}) => {

				commit('UPDATE_CURRENT_CONVERSATION', conversation)
				dispatch('getMessageList')
				let name = ''
				switch (conversation.type) {
					case TIM.TYPES.CONV_C2C:
						name = conversation.userProfile.nick || conversation.userProfile.userID
						break
					case TIM.TYPES.CONV_GROUP:
						name = conversation.groupProfile.name || conversation.groupProfile.groupID
						break
					default:
						name = '系统通知'
				}

				url && uni.navigateTo({
					url: `${url}?toAccount=${name}&type=${conversation.type}&oid=${oid}`
				})
				
				return Promise.resolve()
			})
	},
	onMessageEvent({
			commit,
			state
		},
		event) {
		if (event.name === 'onMessageReceived') {
			let id = state.currentConversationID
			if (!id) return

			let list = []
			event.data.forEach(item => {
				if (item.conversationID === id) {
					list.push(item)
				}
			})
			commit('RECEIVE_MESSAGE', list)
		}
	},
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
